package com.itcast.web.servlet;

import com.itcast.web.dao.UserDao;
import com.itcast.web.domain.User;
import org.apache.commons.beanutils.BeanUtilsBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8");
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtilsBean bean = new BeanUtilsBean();
            bean.populate(user,map);
            User loginUser = new UserDao().login(user);
            if(loginUser!=null){
                request.setAttribute("user",loginUser);
                request.getRequestDispatcher("/successServlet").forward(request,response);
            }else{
                request.getRequestDispatcher("/failServlet").forward(request,response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
